package model

import (
	"webstack/util"

	"gorm.io/gorm"
)

type Web struct {
	ID uint `gorm:"primary_key;AUTO_INCREMENT" json:"id" form:"id"`

	CategoryID  uint32 `gorm:"default:0" form:"category_id" binding:"required" json:"category_id"`
	URI         string `gorm:"type:text;unique" form:"uri" binding:"required" json:"uri"`
	Title       string `gorm:"type:text;default:''" form:"title" binding:"required" json:"title"`
	Description string `gorm:"type:text;default:''" form:"description" binding:"required" json:"description"`
	Img         string `gorm:"type:text" form:"img" binding:"required" json:"img"`
	Private     bool   `gorm:"default:0" form:"private" binding:"required" json:"private"`
}

func (inst *Web) AfterCreate(tx *gorm.DB) (err error) {
	go func() { // 增加额外信息
		data, err := util.UrlCrawler(inst.URI)
		if err != nil {
			return
		}
		db.Model(Web{}).Where("id=?", inst.ID).Updates(map[string]interface{}{
			"img":         data.Image,
			"description": data.Desc,
		})
	}()

	return
}

func (m *Web) Add() (id uint, err error) {
	err = db.Create(&m).Error
	if err == nil {
		id = m.ID
	}
	return
}

func (m *Web) Update() (err error) {
	var cate WebCategory
	db.First(&cate, m.CategoryID)
	if cate.Private {
		m.Private = true
	}
	err = db.Omit("created_at").Model(Web{}).Select("category_id", "uri", "title", "description", "img", "private").Where("id=?", m.ID).Updates(m).Error
	return
}

func DeleteWeb(id uint) (err error) {
	err = db.Where("id=?", id).Delete(&Web{}).Error
	return
}

func GetIncompleteWeb() (webs []Web, err error) {
	err = db.Where("title='' or img='' or description=''").Find(&webs).Error
	return
}

func GetUnCategoryWeb() (webs []Web, err error) {
	err = db.Where("category_id=0").Find(&webs).Error
	return
}

func SetCategoryByIds(ids []uint, cid uint) (err error) {
	err = db.Model(&Web{}).Where("id in ?", ids).Update("category_id", cid).Error
	return
}
